package 剑指offer;

public class p29顺时针打印矩阵 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length==0) {
            return new int[] {};
        }
        int left=0;
        int right=matrix[0].length-1;

        int top=0;
        int bottom=matrix.length-1;

        int[] res=new int[(right+1)*(bottom+1)];
        int x=0;


        while (true) {
            //向右
            for (int i = left; i <= right; i++) {
                res[x]=matrix[top][i];
                x++;
            }
            if (++top>bottom) {
                break;
            }

            //向下
            for (int i=top;i<=bottom;i++) {
                res[x]=matrix[i][right];
                x++;
            }
            if (--right<left) {
                break;
            }
            //向左
            for (int i = right; i >= left ; i--) {
                res[x]=matrix[bottom][i];
                x++;
            }
            if (--bottom<top) {
                break;
            }
            //向上
            for (int i = bottom; i >= top; i--) {
                res[x]=matrix[i][left];
                x++;
            }
            if (++left>right) {
                break;
            }
        }

        return res;
    }
}
